import math
import random
# 加载 Iris 数据集
def load_iris_data():
    data = []
    with open('iris.data', 'r') as f:
        for line in f:
            if line.strip():
                row = line.strip().split(',')
                features = list(map(float, row[:-1]))
                label = row[-1]
                data.append((features, label))
    return data


# 计算欧氏距离
def euclidean_distance(point1, point2):
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2)))


# KNN 分类算法
def knn_classify(train_data, test_point, k):
    distances = []
    for features, label in train_data:
        distance = euclidean_distance(features, test_point)
        distances.append((distance, label))
    distances.sort(key=lambda x: x[0])  # 按距离排序
    nearest_neighbors = distances[:k]
    labels = [label for _, label in nearest_neighbors]
    return max(set(labels), key=labels.count)  # 多数表决


# 划分训练集和测试集
def train_test_split(data, test_size=0.2):
    random.shuffle(data)
    split_index = int(len(data) * (1 - test_size))
    return data[:split_index], data[split_index:]


# 主函数
if __name__ == "__main__":
    # 加载数据
    data = load_iris_data()
    train_data, test_data = train_test_split(data)

    k = 3  # 最近邻数量
    correct = 0
    total = len(test_data)

    for features, label in test_data:
        prediction = knn_classify(train_data, features, k)
        if prediction == label:
            correct += 1

    accuracy = correct / total
    print(f"KNN 分类准确率: {accuracy * 100:.2f}%")


